package com.lqs.sofp.servlet;

import com.alibaba.fastjson.JSON;
import com.lqs.sofp.entity.Text;
import com.lqs.sofp.entity.User;
import com.lqs.sofp.service.TextService;
import com.lqs.sofp.service.impl.TextServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet(name = "addTextServlet", value = "/Text/addText")
public class AddTextServlet extends HttpServlet {
    //private Article article = new Article();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求体数据
        BufferedReader reader = request.getReader();
        //JSON数据只有一行
        String params = reader.readLine();

        //将JSON字符串转为字符串
        Text text = JSON.parseObject(params,Text.class);
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("User");
        text.setPoster(user.getUsername());

        //调用service添加
        TextService textService = new TextServiceImpl();
        Boolean flag =  textService.submitText(text);
        if(flag)
            response.getWriter().write("success");
        else
            response.getWriter().write("default");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
